package com.ontheroad.controller;

import cn.modoumama.page.GridDataModel;
import cn.modoumama.page.PageObject;
import com.google.common.collect.Lists;
import com.ontheroad.api.request.CircleRequest;
import com.ontheroad.api.response.Response;
import com.ontheroad.circle.model.CircleModel;
import com.ontheroad.circle.model.CommentModel;
import com.ontheroad.circle.service.CircleService;
import com.ontheroad.core.util.DateUtils;
import com.ontheroad.core.util.StringUtils;
import com.ontheroad.core.web.BaseController;
import com.ontheroad.path.model.PathUserModel;
import com.ontheroad.topic.model.TopicModel;
import com.ontheroad.topic.service.TopicService;
import com.ontheroad.user.model.UserModel;
import com.ontheroad.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by kedong on 2017/11/2 0002.
 */
@Controller
@RequestMapping("circle")
public class CircleController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CircleService circleService;
    @Autowired
    private UserService userService;
    @Autowired
    private TopicService topicService;

    @RequestMapping("init")
    public String init() {
        return "circle/init";
    }

    @RequestMapping("getData")
    @ResponseBody
    public GridDataModel getData(HttpServletRequest request) {
        PageObject po = createPageObject(request);
        GridDataModel model = circleService.getGridDataModelByCondition(po);
        try {
            if (model.getTotal() > 0) {
                List<CircleModel> circleModels = (List<CircleModel>) model.getRows();
                for (CircleModel circle : circleModels) {
                    Integer userId = circle.getUserid();
                    // 查询用户
                    UserModel user = userService.findById(userId);
                    String nick = user.getNick();
                    if (StringUtils.isBlankString(nick)) {
                        nick = user.getMobile();
                    }
                    circle.setNick(nick);

                    // 查询话题
                    List<TopicModel> topicModels = topicService.findByCircleId(circle.getId());
                    String topics = "";
                    if (topicModels != null && topicModels.size() > 0) {
                        for (TopicModel topicModel : topicModels) {
                            topics += topicModel.getName() + ",";
                        }
                        if (topics.length() > 0) {
                            topics = topics.substring(0, topics.length() - 1);
                        }
                    }
                    circle.setTopics(topics);
                }
                model.setRows(circleModels);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    @RequestMapping("setCareChoose")
    public void setHot(HttpServletRequest request, PrintWriter out, Integer type) {
        String msg = "操作成功";
        boolean result = true;
        try {
            String ids = request.getParameter("ids");
            String[] hotIds = ids.split(",");
            if (type == 1) {
                for (String id : hotIds) {
                    circleService.updateCareChooseByIds(Integer.valueOf(id), true);
                }
            } else if (type == 0) {
                for (String id : hotIds) {
                    circleService.updateCareChooseByIds(Integer.valueOf(id), false);
                }
            }
        } catch (Exception e) {
            msg = "系统发生异常！";
            result = false;
        }
        ajaxJsonResponse(out, result, msg);
    }


    @RequestMapping(value = "delete")
    public void delete(HttpServletRequest request, PrintWriter out) {
        logger.debug("method: delete() ");
        String msg = "操作成功";
        boolean result = true;
        try {
            String ids = request.getParameter("ids");
            String[] aDeleteId = ids.split(",");
            for (String id : aDeleteId) {
                circleService.removeById(Integer.valueOf(id));
            }
        } catch (Exception e) {
            msg = "系统发生异常！";
            result = false;
        }
        ajaxJsonResponse(out, result, msg);
    }

    @RequestMapping(value = "detail")
    public String detail(Map map, Integer id) throws Exception {
        CircleRequest request = new CircleRequest();
        request.setCircleId(id);
        Response response = circleService.getCircleDetail(request);
        logger.error("动态详情", response);
        map.putAll(response.getResultMap());
        CircleModel circle = (CircleModel) map.get("circle");

        String images = circle.getImages();
        List<String> list = Lists.newArrayList();
        if (!StringUtils.isEmpty(images)) {
            if (images.contains(",")) {
                list.addAll(Arrays.asList(images.split(",")));
            } else {
                list.add(images);
            }
        }
        map.put("images", list);
        circle.setTime(DateUtils.DateToSocialDate(circle.getCreateTime()));
        PathUserModel path = circle.getPath();
        if (path != null) {
            Double time = path.getTime();
            int hours = new Double(time / 60).intValue();
            int min = new Double(time - hours * 60).intValue();
            String h = hours + "", m = min + "";
            if (hours < 10) {
                h = "0" + hours;
            }
            if (min < 10) {
                m = "0" + min;
            }
            path.setTimeStr(h + ":" + m);
            circle.setPath(path);
        }
        map.put("circle", circle);

        if (map.containsKey("commentList")) {
            List<CommentModel> commentList = (List<CommentModel>) map.get("commentList");
            if (commentList != null && commentList.size() > 0) {
                for (CommentModel commentModel : commentList) {
                    commentModel.setTime(DateUtils.DateToSocialDate(commentModel.getCreateTime()));
                }
            }
            map.put("commentList", commentList);
        }
        return "circle/detail1";
    }
}
